﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TiaoTiaoCode.AutoUpdate.Common.Requests;
using TiaoTiaoCode.AutoUpdate.ServiceCore.IServices;

namespace TiaoTiaoCode.AutoUpdate.WebApi.Controllers
{
    /// <summary>
    /// 升级服务接口
    /// </summary>
    [AllowAnonymous]
    public class UpgradeController : ApiController
    {
        readonly IMainProgramVersionService _mainVersionSer;
        readonly IProgramFileDetailService _fileDetailSer;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainProgramVersionService"></param>
        /// <param name="programFileDetailService"></param>
        public UpgradeController(IMainProgramVersionService mainProgramVersionService, IProgramFileDetailService programFileDetailService)
        {
            _mainVersionSer = mainProgramVersionService;
            _fileDetailSer = programFileDetailService;
        }

        /// <summary>
        /// 检测当前程序是否有更新版本
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost("checkUpgrade")]
        public async Task<IActionResult> CheckHasUpgrade(ProgramUpdateInfoRequest req)
        {
            return Success(await _mainVersionSer.CheckHasUpgrade(req));
        }

        /// <summary>
        /// 获取需要更新的文件列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost("programFiles")]
        public async Task<IActionResult> ProgramFiles(ProgramUpdateInfoRequest req)
        {
            return Success(await _mainVersionSer.ProgramFileDetails(req));
        }

        /// <summary>
        /// 指定文件下载
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        [HttpGet("download")]
        public async Task<IActionResult> DownloadFile(string fileId)
        {
            var path = await _fileDetailSer.GetFileCalatog(fileId);

            return new FileStreamResult(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), "application/octet-stream")
            {
                FileDownloadName = Path.GetFileName(path)
            };
        }

    }
}
